import React, { useState, useEffect, useRef } from 'react';
import * as echarts from 'echarts';
// 引入中国地图数据
// import 'echarts/map/js/china';
import { message, Switch, Select } from 'antd';
import { statisticsApi, marineApi } from '@/api';
import './Dashboard.css';

const Dashboard = () => {
  // 定义状态变量
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [data, setData] = useState(null);
  const [bhData, setBhData] = useState([]);
  const [hhData, setHhData] = useState([]);
  const [dhData, setDhData] = useState([]);
  const [temperatureData, setTemperatureData] = useState([]);
  const [pressureData, setPressureData] = useState([]);
  const [waveData, setWaveData] = useState([]);
  const [preTemperatureData, setPreTemperatureData] = useState([]);
  const [prePressureData, setPrePressureData] = useState([]);
  const [preWaveData, setPreWaveData] = useState({});

  // 定义图表引用
  const chartRefs = {
    ecological: useRef(null), // 生态指标雷达图的DOM引用
    industry: useRef(null),   // 产业发展柱状图的DOM引用
    trend: useRef(null),       // 趋势折线图的DOM引用
    temperature: useRef(null),  // 温度热力图的DOM引用
    tempTrend: useRef(null),    // 海温趋势图
    pressure: useRef(null),     // 气压趋势图
    wave: useRef(null)          // 浪涌周期图
  };

  const onChange = async (value) => {
    await getMarineAreaData(value);
  };

  // 添加预测数据显示开关状态
  const [showPrediction, setShowPrediction] = useState({
    temperature: false,
    pressure: false
  });

  // 添加选中日期状态（用于海温热力图展示）
  const [selectedDate, setSelectedDate] = useState(null);

  // 初始化生态指标雷达图
  const initEcologicalChart = () => {
    // const chart = echarts.init(chartRefs.ecological.current);
    // 先销毁已存在的实例
    const existingChart = echarts.getInstanceByDom(chartRefs.ecological.current);
    if (existingChart) {
      existingChart.dispose();
    }
    const chart = echarts.init(chartRefs.ecological.current);
    const option = {
      title: {
        text: '海洋生态指标分析'  // 图表标题
      },
      tooltip: {
        trigger: 'axis'  // 提示框触发类型：坐标轴触发
      },
      legend: {
        data: ['渤海区域', '黄海区域', '东海区域'],  // 图例数据
        left: '40%',
      },
      radar: {
        axisName: {
          color: '#6e7079',
        },
        indicator: [
          { name: '水质', max: 100 },          // 雷达图的指标，最大值100
          { name: '生物多样性', max: 100 },    // 生物多样性指标
          { name: '污染指数', max: 100 },      // 污染程度指标
          { name: '资源储量', max: 100 },      // 资源储备指标
          { name: '环境承载力', max: 100 }     // 环境承受能力指标
        ],
      },
      series: [{
        name: '生态指标评分',  // 系列名称
        type: 'radar',        // 图表类型：雷达图
        data: [
          {
            value: [50, 50, 85, 95, 50],  // 东海区域的各项指标数值
            name: '渤海区域',
            areaStyle: {
              color: 'rgba(84, 112, 198, 0.3)'  // 填充区域的颜色和透明度
            }
          },
          {
            value: [80, 85, 60, 75, 88],  // 南海区域的各项指标数值
            name: '黄海区域',
            areaStyle: {
              color: 'rgba(103, 194, 58, 0.3)'  // 填充区域的颜色和透明度
            }
          },
          {
            value: [90, 90, 50, 70, 73],  // 东海区域的各项指标数值
            name: '东海区域',
            areaStyle: {
              color: 'rgba(250, 200, 88, 0.3)'  // 填充区域的颜色和透明度
            }
          }
        ]
      }]
    };
    chart.setOption(option);
  };

  // 初始化产业发展柱状图
  const initIndustryChart = () => {
    // const chart = echarts.init(chartRefs.industry.current);
    // 先销毁已存在的实例
    const existingChart = echarts.getInstanceByDom(chartRefs.industry.current);
    if (existingChart) {
      existingChart.dispose();
    }
    const chart = echarts.init(chartRefs.industry.current);
    const option = {
      title: {
        text: '产业发展评分'  // 图表标题
      },
      tooltip: {
        trigger: 'axis',     // 提示框触发类型：坐标轴触发
        axisPointer: {
          type: 'shadow'     // 坐标轴指示器类型：阴影
        }
      },
      legend: {
        data: ['渤海区域', '黄海区域', '东海区域']  // 图例数据
      },
      grid: {
        left: '3%',    // 图表距离容器左侧的距离
        right: '4%',   // 图表距离容器右侧的距离
        bottom: '3%',  // 图表距离容器底部的距离
        containLabel: true  // 是否包含坐标轴标签
      },
      xAxis: {
        type: 'value',  // 数值轴
        boundaryGap: [0, 0.01]  // 坐标轴两边留白策略
      },
      yAxis: {
        type: 'category',  // 类目轴
        data: ['渔业', '航运业', '旅游业', '能源', '养殖业', '生物技术']  // 产业类别
      },
      series: [
        {
          name: '渤海区域',
          type: 'bar',    // 图表类型：柱状图
          data: bhData  // 渤海区域各产业评分
        },
        {
          name: '黄海区域',
          type: 'bar',    // 图表类型：柱状图
          data: hhData  // 黄海区域各产业评分
        },
        {
          name: '东海区域',
          type: 'bar',    // 图表类型：柱状图
          data: dhData  // 东海区域各产业评分
        }
      ]
    };
    chart.setOption(option);
  };

  // 初始化趋势折线图
  const initTrendChart = () => {
    // const chart = echarts.init(chartRefs.trend.current);
    // 先销毁已存在的实例
    const existingChart = echarts.getInstanceByDom(chartRefs.trend.current);
    if (existingChart) {
      existingChart.dispose();
    }
    const chart = echarts.init(chartRefs.trend.current);
    const option = {
      title: {
        text: '综合评分趋势'  // 图表标题
      },
      tooltip: {
        trigger: 'axis'  // 提示框触发类型：坐标轴触发
      },
      legend: {
        data: ['渤海区域', '黄海区域', '东海区域']  // 图例数据
      },
      grid: {
        left: '3%',    // 图表距离容器左侧的距离
        right: '4%',   // 图表距离容器右侧的距离
        bottom: '3%',  // 图表距离容器底部的距离
        containLabel: true  // 是否包含坐标轴标签
      },
      xAxis: {
        type: 'category',  // 类目轴
        boundaryGap: false,  // 坐标轴两边不留白
        data: ['1月', '3月', '5月', '7月', '9月', '11月']  // 月份数据
      },
      yAxis: {
        type: 'value'  // 数值轴
      },
      series: [
        {
          name: '渤海区域',
          type: 'line',  // 图表类型：折线图
          data: [82, 70, 60, 55, 66, 80],  // 渤海区域各月份评分
          smooth: true   // 启用平滑曲线
        },
        {
          name: '黄海区域',
          type: 'line',  // 图表类型：折线图
          data: [85, 75, 55, 45, 76, 86],  // 黄海区域各月份评分
          smooth: true   // 启用平滑曲线
        },
        {
          name: '东海区域',
          type: 'line',  // 图表类型：折线图
          data: [88, 83, 86, 80, 84, 90],  // 东海区域各月份评分
          smooth: true   // 启用平滑曲线
        }
      ]
    };
    chart.setOption(option);
  };

  // 初始化温度热力图
  const initTemperatureChart = () => {
    if (!data?.temperature?.heatmap_data || data.temperature.heatmap_data.length === 0) {
      console.warn('No temperature heatmap data available');
      return;
    }
    const chart = echarts.init(chartRefs.temperature.current);
    
    const option = {
      title: {
        text: '黄海海域温度日均分布',
        left: 'center',
        textStyle: {
          fontSize: 16,
          fontWeight: 'bold'
        }
      },
      tooltip: {
        trigger: 'item',
        formatter: function(params) {
          return `温度: ${params.value[2]}°C<br>位置: (${params.value[0].toFixed(4)}°E, ${params.value[1].toFixed(4)}°N)`;
        }
      },
      grid: {
        left: '12%',
        right: '10%',
        top: '15%',
        bottom: '25%'  // 增加底部空间，为图例腾出位置
      },
      xAxis: {
        type: 'value',
        name: '经度 (°E)',
        nameLocation: 'middle',
        nameGap: 35,
        min: 'dataMin',
        max: 'dataMax'
      },
      yAxis: {
        type: 'value',
        name: '纬度 (°N)',
        nameLocation: 'middle',
        nameGap: 45,
        min: 'dataMin',
        max: 'dataMax'
      },
      visualMap: {
        min: 20,
        max: 35,
        calculable: true,
        inRange: {
          color: [
            '#313695',
            '#4575b4',
            '#74add1',
            '#abd9e9',
            '#e0f3f8',
            '#ffffbf',
            '#fee090',
            '#fdae61',
            '#f46d43',
            '#d73027',
            '#a50026'
          ]
        },
        orient: 'horizontal',
        left: 'center',
        bottom: '5%'
      },
      series: [{
        name: '海温',
        type: 'scatter',
        data: data.temperature.heatmap_data.map(item => [
          item.lng,
          item.lat,
          item.value
        ]),
        symbolSize: 20,
        itemStyle: {
          opacity: 0.8,
          shadowBlur: 10,
          shadowColor: 'rgba(0, 0, 0, 0.3)'
        }
      }]
    };
    
    chart.setOption(option);
  };

  // 初始化海温趋势图
  const initTempTrendChart = () => {
    if (!data?.marineData?.temperature?.history) {
      console.warn('Missing temperature data');
      return;
    }
    const chart = echarts.init(chartRefs.tempTrend.current);
    
    const option = {
      title: {
        text: '海温趋势图'
      },
      tooltip: {
        trigger: 'axis',
        formatter: function(params) {
          const time = new Date(params[0].value[0]);
          return `${time.getFullYear()}-${time.getMonth()+1}-${time.getDate()}<br/>
                  温度: ${params[0].value[1]}°C`;
        }
      },
      legend: {
        data: ['历史数据', '预测数据']
      },
      xAxis: {
        type: 'time',
        axisLabel: {
          formatter: function(value) {
            const date = new Date(value);
            return `${date.getMonth()+1}-${date.getDate()} ${date.getHours()}`;
          }
        }
      },
      yAxis: {
        type: 'value',
        name: '温度 (°C)',
        nameLocation: 'middle',
        nameGap: 30
      },
      series: [
        {
          name: '历史数据',
          type: 'line',
          data: temperatureData.map(item => [
            item.time,
            item.value
          ]),
          itemStyle: {
            color: '#409EFF'
          }
        },
        {
          name: '预测数据',
          type: 'line',
          data: showPrediction.temperature ? preTemperatureData.map(item => [
            item.time,
            item.value
          ]) : [],
          itemStyle: {
            color: '#F56C6C'
          },
          lineStyle: {
            type: 'dashed'
          }
        }
      ]
    };
    
    chart.setOption(option);
  };

  // 初始化气压趋势图
  const initPressureChart = () => {
    if (!data?.marineData?.pressure?.history) {
      console.warn('Missing pressure data');
      return;
    }
    const chart = echarts.init(chartRefs.pressure.current);
    
    const option = {
      title: {
        text: '气压趋势图'
      },
      tooltip: {
        trigger: 'axis',
        formatter: function(params) {
          const time = new Date(params[0].value[0]);
          return `${time.getFullYear()}-${time.getMonth()+1}-${time.getDate()}<br/>
                  气压: ${params[0].value[1]} hPa`;
        }
      },
      xAxis: {
        type: 'time',
        axisLabel: {
          formatter: function(value) {
            const date = new Date(value);
            return `${date.getMonth()+1}-${date.getDate()} ${date.getHours()}`;
          }
        }
      },
      yAxis: {
        type: 'value',
        name: '气压 (hPa)',
        nameLocation: 'middle',
        nameGap: 30
      },
      series: [
        {
          name: '历史数据',
          type: 'line',
          data: pressureData.map(item => [
            item.time,
            item.value
          ]),
          itemStyle: { color: '#409EFF' }
        },
        {
          name: '预测数据',
          type: 'line',
          data: showPrediction.pressure ? 
            prePressureData.map(item => [
              item.time,
              item.value
            ]) : [],
          itemStyle: { color: '#F56C6C' },
          lineStyle: { type: 'dashed' }
        }
      ]
    };
    
    chart.setOption(option);
  };

  // 初始化浪涌周期图
  const initWaveChart = () => {
    if (!data?.marineData?.wave?.data) {
      console.warn('Missing wave data');
      return;
    }
    const chart = echarts.init(chartRefs.wave.current);
    
    const option = {
      title: {
        text: '浪涌高度图',
        subtext: `平均峰值周期：${preWaveData.average_wave_period.toFixed(3)}天\n\n下一阈值预计${preWaveData.next_peak_days}天后`
      },
      tooltip: {
        trigger: 'axis',
        formatter: function(params) {
          const time = new Date(params[0].value[0]);
          return `${time.getFullYear()}-${time.getMonth()+1}-${time.getDate()}<br/>
                  浪高: ${params[0].value[1]}m`;
        }
      },
      xAxis: {
        type: 'time',
        axisLabel: {
          formatter: function(value) {
            const date = new Date(value);
            return `${date.getMonth()+1}-${date.getDate()} ${date.getHours()}`;
          }
        }
      },
      yAxis: {
        type: 'value',
        name: '浪高 (m)',
        nameLocation: 'middle',
        nameGap: 30
      },
      series: [
        {
          type: 'line',
          data: waveData.map(item => [
            item.time,
            item.value
          ]),
          itemStyle: {
            color: '#67C23A'
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              {
                offset: 0,
                color: 'rgba(103,194,58,0.5)'
              },
              {
                offset: 1,
                color: 'rgba(103,194,58,0.1)'
              }
            ])
          },
          smooth: true
        }
      ]
    };
    
    chart.setOption(option);
  };

  const fetchData = async () => {
    try {
      setLoading(true);
      // 获取原有的数据
      const overview = await statisticsApi.getOverview();
      const areas = await marineApi.getAllAreas();
      
      if (areas && areas.length > 0) {
        const areaId = areas[0].id;
        // 分开获取原有数据和新数据
        const [ecological, industry, trends, temperature, marineData] = await Promise.all([
          marineApi.getEcologicalIndicators(areaId),
          marineApi.getIndustryScores(areaId),
          marineApi.getIndustryTrends(areaId),
          marineApi.getTemperatureHeatmap(areaId),
          marineApi.getMarineData(areaId)  // 新增的数据
        ]);
        
        // 分开设置数据
        setData({
          // 原有的数据
          overview,
          areas,
          ecological,
          industry,
          trends,
          temperature,
          // 新增的数据
          marineData
        });

        const res1 = await marineApi.getAreaScores(3);
        const res2 = await marineApi.getAreaScores(4);
        const res3 = await marineApi.getAreaScores(5);
        setBhData(res1.scores.map(item => item.score));
        setHhData(res2.scores.map(item => item.score));
        setDhData(res3.scores.map(item => item.score));
      }

      await getMarineAreaData(3);
      setLoading(false);
    } catch (err) {
      console.error('fetchData error:', err);
      setError(err.message);
      setLoading(false);
      message.error('获取数据失败');
    }
  };

  // 首次加载时获取数据
  useEffect(() => {
    fetchData();
  }, []);

  const getMarineAreaData = async (areaId) => {
    // 获取海域数据 -- 默认渤海
    const res4 = await marineApi.getStationData(areaId);
    const res4Data = res4.data;
    const res5 = await marineApi.getPredictionData(areaId);
    // console.log('res5:', res5);
    // console.log('res5.forecast:', res5.forecast);
    const temperatureData = res5.forecast.map(item => {
      return {
        time: item.ds,
        value: item.Sea_Temperature_Prediction
      }
    })
    const pressureData = res5.forecast.map(item => {
      return {
        time: item.ds,
        value: item.Air_Pressure_Prediction
      }
    })
    const waveData = {
      'average_wave_period': res5.average_wave_period,
      'next_peak_days': res5.next_peak_days,
    }
    // console.log('temperatureData:', temperatureData);
    // console.log('pressureData:', pressureData);
    // console.log('waveData:', waveData);
    setTemperatureData(res4Data.map(item => {
      return {
        time: '2025-05-' + item.Date,
        value: item.Sea_Temperature + 1
      }
    }));
    setPressureData(res4Data.map(item => {
      return {
        time: '2025-05-' + item.Date,
        value: item.Air_Pressure
      }
    }));
    setWaveData(res4Data.map(item => {
      return {
        time: '2025-05-' + item.Date,
        value: item.Wind_Wave_Height
      }
    }));
    setPreTemperatureData(temperatureData);
    setPrePressureData(pressureData);
    setPreWaveData(waveData);
    // console.log('setPreTemperatureData:', preTemperatureData);
    // console.log('setPrePressureData:', prePressureData);
    // console.log('setPreWaveData:', preWaveData);
  }

  // 数据加载完成后初始化图表
  useEffect(() => {
    if (!loading && !error && data) {
      // 检查必要的数据是否存在
      if (data.ecological) {
        initEcologicalChart();
      }
      if (data.industry) {
        initIndustryChart();
      }
      if (data.trends) {
        initTrendChart();
      }
      if (data.temperature) {
        initTemperatureChart();
      }

      // 添加窗口大小变化的监听
      const handleResize = () => {
        Object.values(chartRefs).forEach(ref => {
          if (ref.current) {
            const chart = echarts.getInstanceByDom(ref.current);
            if (chart) {
              chart.resize();
            }
          }
        });
      };

      window.addEventListener('resize', handleResize);
      return () => {
        window.removeEventListener('resize', handleResize);
        // 销毁图表实例
        Object.values(chartRefs).forEach(ref => {
          if (ref.current) {
            const chart = echarts.getInstanceByDom(ref.current);
            if (chart) {
              chart.dispose();
            }
          }
        });
      };
    }
  }, [loading, error, data]);

  // 新增一个单独的 useEffect 处理新图表
  useEffect(() => {
    if (!loading && !error && data?.marineData) {
      if (data.marineData.temperature) {
        initTempTrendChart();
      }
      if (data.marineData.pressure) {
        initPressureChart();
      }
      if (data.marineData.wave) {
        initWaveChart();
      }
    }
  }, [loading, error, data?.marineData, showPrediction, selectedDate, temperatureData, pressureData, waveData,
    preTemperatureData, prePressureData, preWaveData]);

  // 渲染组件
  return (
    <div className="dashboard-container">
      {/* 面包屑导航 */}
      <div className="inner-banner">
        <section className="w3l-breadcrumb">
          <div className="container">
            <ul className="breadcrumbs-custom-path">
              <li><a href="/">首页</a></li>
              <li className="active"><span className="fa fa-chevron-right mx-2" aria-hidden="true"></span> 数据总览</li>
            </ul>
          </div>
        </section>
      </div>
      {/* 加载状态和错误提示 */}
      {/* {loading && <div className="loading">加载中...</div>}
      {error && <div className="error">错误: {error}</div>} */}
      {/* 主要内容区域 */}
      <div className="dashboard-content">
        <h2 className="dashboard-title">海洋生态数据总览</h2>
        <div className="dashboard-grid">
          <div className="chart-card">
            <div ref={chartRefs.ecological} className="chart"></div>
          </div>
          <div className="chart-card">
            <div ref={chartRefs.industry} className="chart"></div>
          </div>
          <div className="chart-card">
            <div ref={chartRefs.trend} className="chart"></div>
          </div>
        </div>
        <div className="dashboard-grid">
          <div className="chart-card">
            <div ref={chartRefs.temperature} className="chart"></div>
          </div>
        </div>

        {/* 新增的图表区域 */}
        <div className="dashboard-herder">
          <h2 className="dashboard-title">海洋环境实时监测</h2>
          <Select
            placeholder="请选择海域"
            optionFilterProp="label"
            onChange={onChange}
            style={{width: '150px'}}
            defaultValue="3"
            options={[
              {
                value: '3',
                label: '渤海',
              },
              {
                value: '4',
                label: '黄海',
              },
              {
                value: '5',
                label: '东海',
              },
            ]}
          />
        </div>
        <div className="dashboard-grid">
          <div className="chart-card">
            <div className="chart-header">
              <h3>海温趋势</h3>
              <Switch
                checked={showPrediction.temperature}
                onChange={(checked) => setShowPrediction(prev => ({
                  ...prev,
                  temperature: checked
                }))}
                checkedChildren="显示预测"
                unCheckedChildren="隐藏预测"
              />
            </div>
            <div ref={chartRefs.tempTrend} className="chart"></div>
          </div>
          
          <div className="chart-card">
            <div className="chart-header">
              <h3>气压趋势</h3>
              <Switch
                checked={showPrediction.pressure}
                onChange={(checked) => setShowPrediction(prev => ({
                  ...prev,
                  pressure: checked
                }))}
                checkedChildren="显示预测"
                unCheckedChildren="隐藏预测"
              />
            </div>
            <div ref={chartRefs.pressure} className="chart"></div>
          </div>
        </div>

        {/* 浪涌周期图单独一行 */}
        <div className="dashboard-grid single-chart">
          <div className="chart-card">
            <div className="chart-header">
              <h3>浪涌周期</h3>
            </div>
            <div ref={chartRefs.wave} className="chart"></div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Dashboard;